﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using InSolve.dmach.Mail;
using InSolve.dmach.Mail.Decoders;

namespace test
{
    public partial class Form1 : Form, IMessageConstructor
    {
        FileInfo CurrentMessage;
        DecoderSelector Decoders = new DecoderSelector();

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonFileList_Click(object sender, EventArgs e)
        {
            DirectoryInfo d = new DirectoryInfo(@"C:\! In\cnm");

            listViewFiles.BeginUpdate();
            try
            {
                foreach (var f in d.GetFiles("*.cnm"))
                    listViewFiles.Items.Add(
                        new ListViewItem() { Tag = f, Text = f.Name }
                        );
            }
            finally
            {
                listViewFiles.EndUpdate();
            }
        }

        private void buttonNotepad_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewFiles.SelectedItems)
                Process.Start("notepad.exe", "\"" + ((FileInfo)item.Tag).FullName + "\"");
        }


        #region IMessageConstructor Members

        public void AddHeader(string name, string value)
        {
            if (textBoxHeaders.Text.Length > 0)
                textBoxHeaders.Text += Environment.NewLine;

            textBoxHeaders.Text += string.Format("{0}: {1}", name, value);
        }

        public IAttachmentConstructor GetAttachmentConstructor(HeaderCollection headers)
        {
            AttachmentFormat format = headers.GetAttachmentFormat();
            bool requiredBody = false;
            FileInfo file = null;
            Stream stream = null;

            if (format == AttachmentFormat.Html)
            {
                requiredBody = true;
                file = new FileInfo(CurrentMessage.FullName + ".html");
                stream = file.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
            }
            else if (format == AttachmentFormat.PlainText)
            {
                requiredBody = true;
                file = new FileInfo(CurrentMessage.FullName + ".txt");
                stream = new MemoryStream();
            }

            Attachment att = new Attachment(headers, stream, Decoders, requiredBody, (err, comm) => ErrorHandler(err, comm));
            att.TagFile = file;
            return att;
        }

        public void CompleteAttachment(IAttachmentConstructor att)
        {
            Attachment a = (Attachment)att;
            a.CloseInnerStream();

            if (a.IsAttachmentMessageBody)
            {
                if (a.IsAttachmentMessageBodyHtml)
                    webBrowserTextHtml.Navigate(new Uri(a.TagFile.FullName));
                else if (a.IsAttachmentMessageBodyTextPlain)
                {
                    using (var s = a.TagFile.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                    {
                        StreamWriter w = new StreamWriter(s, Encoding.GetEncoding(1251));
                        byte[] data = a.ToArray();
                        w.Write(a.Headers.GetEncoding().GetString(data));
                        w.Flush();
                    }

                    webBrowserTextPlain.Navigate(new Uri(a.TagFile.FullName));
                }
            }
            else
                AddAlertText(a.ToString());
        }

        public void CompleteConstruction()
        {
        }

        public void ErrorHandler(ParserError err, string comment)
        {
            AddAlertText(string.Format("{0}: {1}", err, comment));
        }

        private void AddAlertText(string text)
        {
            if (textBoxErrors.Text.Length > 0)
                textBoxErrors.Text += Environment.NewLine;
            else
                textBoxErrors.BackColor = Color.Bisque;

            textBoxErrors.Text += text;
        }

        #endregion

        private void listViewFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewFiles.SelectedItems.Count > 0)
            {
                CurrentMessage = listViewFiles.SelectedItems[0].Tag as FileInfo;
                if (CurrentMessage == null)
                    return;

                textBoxHeaders.Text = "";
                textBoxErrors.Text = "";
                textBoxErrors.BackColor = SystemColors.Window;
                webBrowserTextHtml.Url = null;
                webBrowserTextPlain.Url = null;

                Parser.Parse(this, CurrentMessage.OpenRead());
            }
        }

        private void buttonCopy_Click(object sender, EventArgs e)
        {
            string dir_target = "isolator";

            if (CurrentMessage != null)
            {
                string dir_target_full = Path.Combine(CurrentMessage.Directory.FullName, dir_target);
                if (!Directory.Exists(dir_target_full))
                    Directory.CreateDirectory(dir_target_full);

                string file_target_full = Path.Combine(dir_target_full, CurrentMessage.Name);
                if (!File.Exists(file_target_full))
                    CurrentMessage.CopyTo(file_target_full);
            }
        }
    }
}
